package stewardapp

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/shopspring/decimal"
	"log"
	"strconv"
	"time"
	"yundian/internel/app/helper/resphelper/placeresp"
	"yundian/internel/app/models/membermodel"
	"yundian/internel/app/models/placemodel"
	"yundian/internel/pkg/authorized"
	"yundian/internel/app/dao"
	"yundian/internel/app/helper"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/logic"
	"yundian/internel/app/models/devices"
	"yundian/internel/app/models/orders"
	"yundian/internel/app/models/ordersstatistics"
	"yundian/internel/app/models/prices"
	"yundian/internel/app/models/userprofitlog"
	"yundian/internel/app/models/users"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
	. "yundian/internel/pkg/dingo/result"
	"yundian/internel/pkg/utils"
	"yundian/internel/pkg/wechatpay"
)

// HandleGetRoomCash 查询商品续住可提现金额
func HandleGetRoomCash(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	param := &request.OrdersCashReq{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()
	param.UserId = userId

	data := dao.NewRoomDaoDao().GetRoomOrdersToCashByUserId(param)
	if data.Err != nil {
		Response(ctx)("", CodeInternalServerError, nil)(OK)
		return
	}

	Response(ctx)("", CodeSuccess, data.Unwrap())(OK)
}

// HandleGetGoodsCash 查询商品订单可提现金额
func HandleGetGoodsCash(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	param := &request.OrdersCashReq{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()
	param.UserId = userId

	data := dao.NewGoodsDao().GetGoodsOrdersToCashByUserId(param)
	if data.Err != nil {
		Response(ctx)("", CodeInternalServerError, nil)(OK)
		return
	}

	Response(ctx)("", CodeSuccess, data.Unwrap())(OK)
}

// 获取设备总条数
func HandleDeviceCount(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()
	userInfo := dao.NewUserDao().GetUserInfoByUserId(userId).Unwrap().(users.UserInfoPlaceId)
	Response(ctx)(
		"",
		CodeSuccess,
		dao.NewDeviceDao().GetDeviceCountByPlaceId(userInfo.PlaceId).Unwrap(),
	)(OK)
}

// 获取代理商设备总条数
func HandleAgentDeviceCount(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()
	IsAdmin, _ := helper.GetIsAdminFromCtx(ctx)
	IsPlace, _ := helper.GetIsPlaceFromCtx(ctx)

	deviceTotal := dao.NewDeviceDao().GetDeviceCountByAgentId(userId, IsAdmin, IsPlace).Unwrap().(int64)
	usedDeviceTotal := dao.NewDeviceDao().GetDeviceUsedCountByAgentId(userId, IsAdmin, IsPlace).Unwrap().(int64)

	Response(ctx)("", CodeSuccess, &struct {
		Total     int64 `json:"total"`
		UsedTotal int64 `json:"usedTotal"`
	}{
		Total:     deviceTotal,
		UsedTotal: usedDeviceTotal,
	})(OK)
}

// 获取订单总条数
func HandleOrderCount(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()
	userInfo := dao.NewUserDao().GetUserInfoByUserId(userId).Unwrap().(users.UserInfoPlaceId)
	Response(ctx)(
		"",
		CodeSuccess,
		dao.NewOrderDao().CountOrderByPlaceId(userInfo.PlaceId).Unwrap(),
	)(OK)
}

// 获取订单总条数
func HandleAgentOrderCount(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()
	IsDraw, _ := helper.GetIsDrawFromCtx(ctx)
	IsAdmin, _ := helper.GetIsAdminFromCtx(ctx)
	Response(ctx)(
		"",
		CodeSuccess,
		dao.NewOrderDao().CountOrderByAgentId(userId, IsDraw, IsAdmin).Unwrap(),
	)(OK)
}

//
func HandleAgentTradeTotal(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	param := &struct {
		Day int `json:"day" form:"day"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()
	IsAdmin, _ := helper.GetIsAdminFromCtx(ctx)
	IsPlace, _ := helper.GetIsPlaceFromCtx(ctx)
	IsDraw, _ := helper.GetIsDrawFromCtx(ctx)

	tradeTotal := dao.NewOrderDao().CountTradeTotalByAgentId(userId, param.Day, IsAdmin, IsPlace, IsDraw).Unwrap().(int64) // 获取某天前的交易总额
	servingTotal := dao.NewOrderDao().CountOrderStatusByAgentId(userId, param.Day, 2, IsAdmin, IsDraw).Unwrap().(int64)    // 借出笔数
	returnedTotal := dao.NewOrderDao().CountOrderStatusByAgentId(userId, param.Day, 5, IsAdmin, IsDraw).Unwrap().(int64)   // 还入笔数

	var TradeTotal = "0"
	var Price = "0"
	if tradeTotal > 0 {
		TradeTotal = decimal.NewFromInt(tradeTotal).Div(decimal.NewFromInt(100)).StringFixed(2)
	}
	if returnedTotal > 0 && tradeTotal > 0 {
		Price = decimal.NewFromInt(tradeTotal).Div(decimal.NewFromInt(returnedTotal)).Div(decimal.NewFromInt(100)).StringFixed(4) // 客单价 = 交易总额 / 还入笔数
	}
	data := &struct {
		TradeTotal    string `json:"tradeTotal"`
		ReturnedTotal int64  `json:"returnedTotal"`
		ServingTotal  int64  `json:"servingTotal"`
		Price         string `json:"price"`
	}{
		TradeTotal:    TradeTotal,
		ReturnedTotal: returnedTotal,
		ServingTotal:  servingTotal,
		Price:         Price,
	}
	Response(ctx)("", CodeSuccess, data)(OK)
}

// HandleGetDeviceList 获取设备列表
func HandleGetDeviceList(ctx *gin.Context) {
	//userInfo := dao.NewUserDao().GetUserInfoByUserId(userId).Unwrap().(users.UserInfoPlaceId)
	// 请求参数处理
	param := &request.DeviceListByPlaceReq{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()
	param.UserId = userId
	param.IsAdmin, _ = helper.GetIsAdminFromCtx(ctx)
	param.IsPlace, _ = helper.GetIsPlaceFromCtx(ctx)

	// 获取数据
	data := dao.NewDeviceDao().LoadDeviceListWithTypeByPlace(param)
	// 响应请求
	Response(ctx)("", CodeSuccess, ResponseList{
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  (data.Val().(int64) + int64(param.PageSize) - 1) / int64(param.PageSize),
		Data:       data.Unwrap(),
	})(OK)
}

// 获取商户价格
func HandleGetPlacePrice(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()
	userInfo := dao.NewUserDao().GetUserInfoByUserId(userId).Unwrap().(users.UserInfoPlaceId)
	// 获取商户所拥有的设备
	lists := dao.NewDeviceDao().GetPlaceBindDeviceType(userInfo.PlaceId).Unwrap().([]*devices.DeviceTypeIdByPlace)
	for _, lst := range lists {
		limit := 1
		if lst.DeviceTypeId == 12 {
			limit = 10
		} // 多套餐密码线
		lst.RuleInfo = dao.NewPricesDao().GetPlacePriceByTypeId(userInfo.PlaceId, lst.DeviceTypeId, limit, 0, "").Unwrap().([]prices.PriceModel)
	}

	Response(ctx)("", CodeSuccess, lists)(OK)
}

// 获取商户订单
func HandleGetPlaceOrders(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	isAdmin, _ := helper.GetIsAdminFromCtx(ctx)
	IsDraw, _ := helper.GetIsDrawFromCtx(ctx)
	//userInfo := dao.NewUserDao().GetUserInfoByUserId(userId).Unwrap().(users.UserInfoPlaceId)
	//param.PlaceId = userInfo.PlaceId

	// 获取商户订单
	param := &request.OrderListByPlaceReq{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()
	param.LoginUserId = userId
	param.IsAdmin = isAdmin
	param.IsDraw = IsDraw

	data := dao.NewOrderDao().GetOrderListByPlace(param)

	Response(ctx)("", CodeSuccess, ResponseList{
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  (data.Val().(int64) + int64(param.PageSize) - 1) / int64(param.PageSize),
		Data:       data.Unwrap(),
	})(OK)
}

// 获取代理商订单
func HandleGetAgentOrders(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()
	IsDraw, _ := helper.GetIsDrawFromCtx(ctx)
	IsAdmin, _ := helper.GetIsAdminFromCtx(ctx)

	// 获取商户订单
	param := &request.OrderListByPlaceReq{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()
	param.LoginUserId = userId
	param.IsAdmin = IsAdmin
	param.IsDraw = IsDraw

	//data := dao.NewOrderDao().GetOrderListByAgent(param, userId, IsDraw, IsAdmin)
	data := dao.NewOrderDao().GetOrderListByPlace(param)

	Response(ctx)("", CodeSuccess, ResponseList{
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  (data.Val().(int64) + int64(param.PageSize) - 1) / int64(param.PageSize),
		Data:       data.Unwrap(),
	})(OK)
}

// 获取代理下的商户收益排行
func HandleGetPlaceIncomeRank(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	param := &request.PlaceIncomeRankByAgent{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()
	IsAdmin, _ := helper.GetIsAdminFromCtx(ctx)
	IsPlace, _ := helper.GetIsPlaceFromCtx(ctx)

	data := dao.NewOrderDao().GetPlaceIncomeRankByAgent(param, userId, IsAdmin, IsPlace)

	lists := data.Unwrap().([]*ordersstatistics.PlaceIncomeByDay)

	for _, lst := range lists {
		lst.DeviceCount = dao.NewDeviceDao().GetDeviceCountByPlaceId(lst.PlaceId).Unwrap().(int64)
	}

	totalCount := data.Val().(int64)
	if param.PageSize > len(lists) {
		totalCount = int64((param.PageNo-1)*param.PageSize + len(lists))
	}

	Response(ctx)("", CodeSuccess, ResponseList{
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: totalCount,
		TotalPage:  (totalCount + int64(param.PageSize) - 1) / int64(param.PageSize),
		Data:       lists,
	})(OK)
}

// 获取商户提现记录
func HandleGetPlaceCash(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()
	//userInfo := dao.NewUserDao().GetUserInfoByUserId(userId).Unwrap().(users.UserInfoPlaceId)
	param := &request.CashListReq{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()
	param.UserId = userId

	data := dao.NewCashDao().GetCashList(param)

	Response(ctx)("", CodeSuccess, ResponseList{
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  (data.Val().(int64) + int64(param.PageSize) - 1) / int64(param.PageSize),
		Data:       data.Unwrap(),
	})(OK)
}

// 计算商户可提现金额
func HandleGetCashMoney(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()
	// 计算已提现金额(处理成功的)
	cashTotal := dao.NewOrderDao().GetCashLogByUserId(userId).Unwrap().(int64)
	log.Println("打印测试数据--已提现金额", cashTotal)

	// 计算分红总金额
	dividTotal := dao.NewOrderDao().GetDividendsMoneyByUserId(userId).Unwrap().(int64)
	log.Println("打印测试数据--分红总金额", dividTotal)

	// 当天分红金额
	nowDividTotal := dao.NewOrderDao().GetTodayDividendsMoneyByUserId(userId).Unwrap().(int64)
	log.Println("打印测试数据--当天分红金额", nowDividTotal)

	// 总分红 - 已提现 = 可提现金额
	cashMoney := decimal.NewFromInt(dividTotal).Sub(decimal.NewFromInt(cashTotal))
	log.Println("打印测试数据--可提现金额", cashMoney)

	//c, _ := decimal.NewFromInt(dividTotal).Sub(decimal.NewFromInt(cashTotal)).Float64()
	//
	//if c < float64(0) {
	//	// 提现的金额    大于   订单分红金额  ---- 数据异常
	//
	//}

	// 可提现金额 = 分红总金额 - 已提现金额
	Response(ctx)("", CodeSuccess, &struct {
		CashTotal     string `json:"cashTotal"`     // 已提现金额
		DividTotal    string `json:"dividTotal"`    // 分红总额
		CashMoney     string `json:"cashMoney"`     // 可提现
		NowDividTotal string `json:"nowDividTotal"` // 当天收益
	}{
		CashTotal:  decimal.NewFromInt(cashTotal).Div(decimal.NewFromFloat(100)).StringFixed(2),
		DividTotal: decimal.NewFromInt(dividTotal).Div(decimal.NewFromFloat(100)).StringFixed(2),
		//CashMoney:     cashMoney.Div(decimal.NewFromFloat(100)).StringFixed(2),
		CashMoney:     cashMoney.Div(decimal.NewFromInt(100)).StringFixed(2),
		NowDividTotal: decimal.NewFromInt(nowDividTotal).Div(decimal.NewFromFloat(100)).StringFixed(2),
	})(OK)
}

// 计算代理商可提现金额
func HandleGetAgentCashMoney(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()
	// 已提现金额(处理成功的)
	cashTotal := dao.NewOrderDao().GetCashLogByUserId(userId).Unwrap().(int64)
	log.Println("打印测试数据--已提现金额(代理商)", cashTotal)

	// 分红总收益
	dividTotal := dao.NewOrderDao().GetDividendsMoneyByUserId(userId).Unwrap().(int64)
	log.Println("打印测试数据--分红总收益(代理商)", dividTotal)

	// 抽单总收益
	var drawTotal int64 = 0
	//drawTotal := dao.NewOrderDao().GetTakeTotalMoneyByUserId(userId).Unwrap().(int64)
	//log.Println("打印测试数据--抽单总收益(代理商)", drawTotal)

	// 累计收益 = 分红收益 + 抽单收益
	moneyTotal := decimal.NewFromInt(dividTotal).Add(decimal.NewFromInt(drawTotal))
	log.Println("打印测试数据--累计总收益(代理商)", moneyTotal)

	// 可提现金额 =累计收益 - 已提现
	cashMoney := moneyTotal.Sub(decimal.NewFromInt(cashTotal))
	log.Println("打印测试数据--可提现金额(代理商)", cashMoney)

	// 当天分红收益
	nowDividTotal := dao.NewOrderDao().GetTodayDividendsMoneyByUserId(userId).Unwrap().(int64)
	log.Println("打印测试数据--当天分红收益(代理商)", nowDividTotal)

	// 当天抽单收益
	var nowDrawTotal int64 = 0
	//nowDrawTotal := dao.NewOrderDao().GetTodayDrawMoneyByUserId(userId).Unwrap().(int64)
	//log.Println("打印测试数据--当天抽单收益(代理商)", nowDrawTotal)

	// 计算当天总收益 = 当天分红收益 + 当天抽单收益
	nowMoneyTotal := decimal.NewFromInt(nowDividTotal).Add(decimal.NewFromInt(nowDrawTotal))
	log.Println("打印测试数据--当天总收益(代理商)", nowDividTotal)

	//c, _ := decimal.NewFromInt(dividTotal).Sub(decimal.NewFromInt(cashTotal)).Float64()
	//
	//if c < float64(0) {
	//	// 提现的金额    大于   订单分红金额  ---- 数据异常
	//
	//}

	// 可提现金额 = 分红总金额 - 已提现金额
	Response(ctx)("", CodeSuccess, &struct {
		CashTotal     string `json:"cashTotal"`     // 已提现金额
		DividTotal    string `json:"dividTotal"`    // 累计总收益
		CashMoney     string `json:"cashMoney"`     // 可提现
		NowDividTotal string `json:"nowDividTotal"` // 当天总收益
	}{
		CashTotal:     decimal.NewFromInt(cashTotal).Div(decimal.NewFromFloat(100)).StringFixed(2),
		DividTotal:    moneyTotal.Div(decimal.NewFromFloat(100)).StringFixed(2),
		CashMoney:     cashMoney.Div(decimal.NewFromInt(100)).StringFixed(2),
		NowDividTotal: nowMoneyTotal.Div(decimal.NewFromFloat(100)).StringFixed(2),
	})(OK)
}

// 计算每日收益
// 数据量大后，使用定时更新到  收益日志表  -- taskLogic
func HandlePlaceIncome(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	param := &request.IncomeListReq{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param))
	param.UserId = userId

	data := dao.NewOrderDao().GetIncomeList(param)

	Response(ctx)("", CodeSuccess, ResponseList{
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  (data.Val().(int64) + int64(param.PageSize) - 1) / int64(param.PageSize),
		Data:       data.Unwrap(),
	})(OK)
}

// HandlePlaceIncomeDetail 获取收益明细
func HandlePlaceIncomeDetail(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	param := &request.IncomeListReq{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param))
	param.UserId = userId

	data := dao.NewOrderDao().GetIncomeDetailList(param)

	Response(ctx)("", CodeSuccess, ResponseList{
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  (data.Val().(int64) + int64(param.PageSize) - 1) / int64(param.PageSize),
		Data:       data.Unwrap(),
	})(OK)
}

func HandlePlaceWithDrawal(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	//isPlace, err := helper.GetIsPlaceFromCtx(ctx)
	//if err != nil {
	//	Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
	//	return
	//}
	param := &request.WithDrawalReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param))

	param.UserId = userId
	param.ClientIp = ctx.ClientIP()

	err = logic.NewOrderLogic().HandlePlaceTransfers(param)
	if err != nil {
		Response(ctx)(err.Error(), CodeSuccess, false)(OK)
		return
	}
	Response(ctx)("", CodeSuccess, true)(OK)
}

// 国曼提现
func HandlePlaceWithDrawalByGM(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	//isPlace, err := helper.GetIsPlaceFromCtx(ctx)
	//if err != nil {
	//	Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
	//	return
	//}
	param := &request.WithDrawalReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param))

	param.UserId = userId
	param.ClientIp = ctx.ClientIP()

	err = logic.NewOrderLogic().HandlePlaceTransfersByGM(param)
	if err != nil {
		Response(ctx)(err.Error(), CodeSuccess, false)(OK)
		return
	}
	Response(ctx)("", CodeSuccess, true)(OK)
}

func HandleAgentWithDrawal(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	//
	//isPlace, err := helper.GetIsPlaceFromCtx(ctx)
	//if err != nil {
	//	Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
	//	return
	//}

	param := &request.WithDrawalReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param))
	param.UserId = userId
	param.ClientIp = ctx.ClientIP()

	err = logic.NewOrderLogic().HandleAgentTransfers(param)
	if err != nil {
		Response(ctx)(err.Error(), CodeSuccess, false)(OK)
		return
	}
	Response(ctx)("", CodeSuccess, true)(OK)
}

func HandelGetWeixinInfo(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()
	log.Println("获取用户信息-----userId", userId)
	var url string
	//userInfo := dao.NewUserDao().GetUserInfoByUserId(userId).Unwrap().(users.UserInfoPlaceId)
	userInfo := dao.NewUserDao().GetUserInfoById(userId).Unwrap().(*users.UserModel)
	log.Println("获取用户信息-----userInfo", userInfo)
	if userInfo.IsBind == 0 {
		redirectUri := global.Cfg.Wx.RedirectUri + "/user/auth"
		url = fmt.Sprintf("https://open.weixin.qq.com/connect/oauth2/authorize?"+
			"appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo&state=yundian#wechat_redirect", global.Cfg.Wx.AppId, redirectUri)
	}

	Response(ctx)("获取成功", CodeSuccess, &struct {
		UserInfo *users.UserModel `json:"userInfo"`
		Url      string           `json:"url"`
	}{
		UserInfo: userInfo,
		Url:      url,
	})(OK)
}

func HandelGetAgentWeixinInfo(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	var url string
	userInfo := dao.NewUserDao().GetUserInfoById(userId).Unwrap().(*users.UserModel)
	if userInfo.IsBind == 0 {
		redirectUri := global.Cfg.Wx.RedirectUri + "/user/auth"
		url = fmt.Sprintf("https://open.weixin.qq.com/connect/oauth2/authorize?"+
			"appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo&state=yundian#wechat_redirect", global.Cfg.Wx.AppId, redirectUri)
	}

	Response(ctx)("获取成功", CodeSuccess, &struct {
		UserInfo *users.UserModel `json:"userInfo"`
		Url      string           `json:"url"`
	}{
		UserInfo: userInfo,
		Url:      url,
	})(OK)
}

// 修改密码
func HandleUpdateUserPassword(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	if err != nil {
		dingo.ErrorIf(err).Unwrap()
	}
	param := &struct {
		Passoword string `json:"password" binding:"required,min=6"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	password := utils.EncryptPassword(param.Passoword)
	Response(ctx)("", CodeUpdateSuccess, dao.NewUserDao().UpdateUserPassword(userId, password).Unwrap())(OK)

}

// 解绑微信
func HandleUnBindWxInfo(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	if err != nil {
		dingo.ErrorIf(err).Unwrap()
	}
	Response(ctx)("", CodeUpdateSuccess, dao.NewUserDao().UpdateUserIsBind(userId).Unwrap())(OK)

}

// 获取商户列表
func HandleGetPlaceList(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()
	IsAdmin, _ := helper.GetIsAdminFromCtx(ctx)

	param := &request.PlaceListByPlaceReq{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param))
	param.UserId = userId

	placeIds := []int{}
	data := dao.NewPlaceDao().GetPlaceListByPlace(param, IsAdmin)
	lists := data.Unwrap().([]*placeresp.PlacesWithUser)
	// db := global.Orm.Debug().Table("place_income").Select("SUM(income) as total,place_name,place_id")
	for _, lst := range lists {
		// 计算当前商户的总收益
		//lst.Income = decimal.NewFromInt(dao.NewOrderDao().GetUserIncome(lst.UserID).Unwrap().(int64)).Div(decimal.NewFromInt(100)).StringFixed(2)
		lst.Income = fmt.Sprintf("%d", 0)
		placeIds = append(placeIds, lst.Id)

		// 计算当前商户的设备条数
		//lst.DevCount = dao.NewDeviceDao().GetDeviceCountGroupByDeviceTypeId(lst.Id).Unwrap().([]placeresp.PlaceDeviceCount)
	}

	if len(placeIds) > 0 {
		placeIncomeList := dao.NewOrderDao().GetPlaceIncome(placeIds, userId).Unwrap().([]orders.PlaceIncome)
		for _, lst := range lists {
			for _, item := range placeIncomeList {
				if lst.Id == item.PlaceId {
					lst.Income = fmt.Sprintf("%.2f", float32(item.Money)/100)
					break
				}
			}
		}
		devList := dao.NewDeviceDao().GetDeviceCountGroupByDeviceTypeIds(placeIds).Unwrap().([]placeresp.PlaceDeviceCount)
		for _, lst := range lists {
			for _, item := range devList {
				if lst.Id == item.PlaceId {
					lst.DevCount = append(lst.DevCount, item)
				}
			}
		}
	}

	Response(ctx)("", CodeSuccess, ResponseList{
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  (data.Val().(int64) + int64(param.PageSize) - 1) / int64(param.PageSize),
		Data:       lists,
	})(OK)
}

// 保存商户套餐价格配置
func HandleSavePlaceProfit(ctx *gin.Context) {
	param := &struct {
		UserId int `json:"userId"`
		Pcl    int `json:"profitProportion"`
		Sm    int `json:"smProfitProportion"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()

	Response(ctx)("修改成功", CodeSuccess,
		dao.NewUserDao().UpdatePlaceProfit(param.UserId, param.Pcl, param.Sm).Unwrap())(OK)
}

// 获取上级用户信息
func HandleGetUserInfoByPid(ctx *gin.Context) {
	param := &struct {
		ParentId int `form:"parentId"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()
	Response(ctx)(
		"",
		CodeSuccess,
		dao.NewUserDao().GetUserInfoById(param.ParentId).Unwrap(),
	)(OK)
}

// 获取用户信息
func HandleGetUserInfoByUserId(ctx *gin.Context) {
	param := &struct {
		UserId int `form:"userId"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()
	Response(ctx)(
		"",
		CodeSuccess,
		dao.NewUserDao().GetUserInfoById(param.UserId).Unwrap(),
	)(OK)
}

//
func HandleGetParentUserInfoByUserId(ctx *gin.Context) {
	param := &struct {
		UserId int `form:"userId"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()
	userInfo := dao.NewUserDao().GetUserInfoById(param.UserId).Unwrap().(*users.UserModel)
	Response(ctx)(
		"",
		CodeSuccess,
		dao.NewUserDao().GetUserInfoById(userInfo.ParentID).Unwrap(),
	)(OK)
}

// 代理商每日收益明细
func HandleAgentIncome(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()
	IsDraw, _ := helper.GetIsDrawFromCtx(ctx)
	IsAdmin, _ := helper.GetIsAdminFromCtx(ctx)

	param := &request.AgentIncomeListReq{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param))
	param.IsDraw = IsDraw
	param.IsAdmin = IsAdmin

	data := dao.NewAgentCountDao().GetAgentIncomeList(param, userId)

	Response(ctx)("", CodeSuccess, ResponseList{
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  (data.Val().(int64) + int64(param.PageSize) - 1) / int64(param.PageSize),
		Data:       data.Unwrap(),
	})(OK)
}

// 手动完结订单
func HandelCompleteOrder(ctx *gin.Context) {
	param := &request.CloseOrderReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	orderInfo := orders.New()
	global.Orm.Table("orders").
		Where("trade_no = ?", param.TradeNo).
		Find(&orderInfo)
	param.EndTime = time.Now().Unix()
	if param.Openid == "" {
		m := membermodel.New()
		global.Orm.Table("members").Where("uuid = ?", orderInfo.MemberId).Find(m)
		param.Openid = m.XcxOpenid
	}
	log.Println("打印测试数据-后台结算订单请求参数", param)
	respData := logic.NewOrderLogic().HandleWxEndOrder(param)
	log.Println("打印完结订单返回结果 ------ ", respData)
	Response(ctx)("订单完结成功", CodeSuccess, true)(OK)
}

// 恢复抽单订单、恢复奖励订单
func HandelBakOrder(ctx *gin.Context) {
	param := &request.CloseOrderReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	orderInfo := orders.New()
	global.Orm.Table("orders").
		Where("trade_no = ?", param.TradeNo).
		Where("create_at = ?", wechatpay.StrTimeToInt(param.CreateTime)).
		Find(&orderInfo)
	devInfo := dao.NewDeviceDao().FetchDeviceInfoWithType(param.DeviceSn).Unwrap().(*devices.DeviceType)
	if orderInfo.State == 5 {
		dingo.Task(logic.NewOrderLogic().CalOrderDividends, func() {}, orderInfo, devInfo, orderInfo.SettlementMoney, int64(orderInfo.EndAt)) // 计算分红 - 异步任务
	}
	dao.NewOrderDao().UpdateOrderIsDraw(orderInfo)

	Response(ctx)("恢复成功", CodeSuccess, "SUCCESS")(OK)
}

// 微信扫一扫
func HandelGetWxSign(ctx *gin.Context) {
	param := &struct {
		Url string `json:"url" form:"url"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()
	log.Println(param)

	timeStamp := time.Now().Unix()
	nonceStr := utils.GetRandomStringAndInt(16)

	// 判断是否有缓存
	userId, _ := helper.GetUserIdFromCtx(ctx)
	t := global.Rdb.TTL(ctx, utils.Join("jssdk-ticket-key-", strconv.Itoa(userId))).Val()
	if t <= 0 {
		respAccessToken, err := authorized.GetAccessToken(global.Cfg.Wx.AppId, global.Cfg.Wx.AppSecret)
		if err != nil {
			log.Println(err)
		}
		respTicket, err := authorized.GetTicket(respAccessToken.AccessToken)
		if err != nil {
			log.Println(err)
		}
		str := fmt.Sprintf("jsapi_ticket=%s&noncestr=%s&timestamp=%s&url=%s", respTicket.Ticket, nonceStr, strconv.Itoa(int(timeStamp)), param.Url)
		signature := wechatpay.SHA1(str, "")
		res := authorized.SignInfo{
			Appid:     global.Cfg.Wx.AppId,
			NonceStr:  nonceStr,
			TimeStamp: strconv.Itoa(int(timeStamp)),
			Url:       param.Url,
			Signature: signature,
		}
		log.Println("打印测试签名", respTicket.Ticket, nonceStr, timeStamp, param.Url, signature)
		global.Rdb.Set(ctx, utils.Join("jssdk-ticket-key-", strconv.Itoa(userId)), res, time.Second*7200)
		Response(ctx)("", CodeSuccess, res)(OK)
	} else {
		t := authorized.SignInfo{}
		s := global.Rdb.Get(ctx, utils.Join("jssdk-ticket-key-", strconv.Itoa(userId))).Val()
		_ = json.Unmarshal([]byte(s), &t)
		log.Println("打印测试", t)
		Response(ctx)("", CodeSuccess, t)(OK)
	}

}

//单条线绑定
func HandlePclBindIng(c *gin.Context) {
	param := &struct {
		PlaceId  int    `json:"placeId"`
		DeviceSn string `json:"deviceSn"`
	}{}
	dingo.ErrorIf(c.Bind(&param)).Unwrap()
	//查询网点信息
	placesInfo := placemodel.NewPlaceModel()
	placesInfoDb := global.Orm.Debug().Table("places").Where("id = ?", param.PlaceId).Find(&placesInfo)
	if placesInfoDb.Error != nil {
		Response(c)(placesInfoDb.Error.Error(), CodeError, false)(OK)
		return
	}

	m := devices.New()
	m.PlaceId = param.PlaceId
	m.State = 2
	m.PlaceName = placesInfo.PlaceName
	m.DeployAt = dingo.Time(time.Now().Unix())
	m.UpdateAt = dingo.Time(time.Now().Unix())
	db := global.Orm.Debug().Table("devices").Where("device_sn = ?", param.DeviceSn).Updates(&m)
	if db.Error != nil {
		Response(c)(db.Error.Error(), CodeError, false)(OK)
		return
	}
	Response(c)("绑定成功", CodeSuccess, true)(OK)
}

//单条线解绑
func HandlePclUnbind(c *gin.Context) {
	param := &struct {
		PlaceId  int    `json:"placeId"`
		DeviceSn string `json:"deviceSn"`
	}{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	//使用map更新避0值和nil值更新不了
	updateVal := map[string]interface{}{
		"place_id":   0,
		"state":      1,
		"place_name": "",
		"deploy_at":  0,
		"update_at":  dingo.Time(time.Now().Unix()),
	}
	db := global.Orm.Debug().Table("devices").Where("device_sn = ?", param.DeviceSn).Updates(&updateVal)
	if db.Error != nil {
		Response(c)(db.Error.Error(), CodeError, false)(OK)
		return
	}
	Response(c)("解绑成功", CodeSuccess, true)(OK)
}

func HandInsertPlaceUser(c *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(c)
	dingo.ErrorIf(err).Unwrap()
	IsPlace, _ := helper.GetIsPlaceFromCtx(c)
	userName, _ := helper.GetUserNameFromCtx(c)
	param := &request.AdminUserInsertReq{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()

	if IsPlace == helper.TypeNumIsPlaceKa {
		param.KaUserId = userId
	}

	id := dao.NewUserDao().InsertPlaceUser(param).Unwrap().(int)
	if id <= 0 {
		Response(c)("新增失败", CodeError, true)(OK)
		return
	}

	//添加修改用户分成日志
	upl := userprofitlog.UserProfitLog{}
	upl.ParentId = param.ParentId
	upl.UserName = param.UserName
	upl.OperationUserId = userId
	upl.OperationUserName = userName
	upl.OperateIP = c.ClientIP()
	upl.Change = 0
	upl.IsPlace = 1
	upl.ProfitProportion = int8(param.ProfitProportion)
	upl.Description = "新增商户用户"
	upl.UserId = id
	u := &users.UserModel{}
	dingo.Task(logic.NewLogsLogic().InsertUserProfitLogLogic, func() {}, upl, param, u) // 添加订单操作日志
	Response(c)("新增成功", CodeSuccess, true)(OK)
}

// 修改商户用户
func HandleUpdatePlaceUser(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx) // 获取当前登录用户ID
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}

	userName, err := helper.GetUserNameFromCtx(ctx) // 获取当前登录用户名
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	param := &request.AdminUserInsertReq{}
	dingo.ErrorIf(ctx.Bind(param)).Unwrap()
	//添加修改用户分成日志

	//查询该用户修改前的分成比例
	userInfo := dao.NewUserDao().GetUserInfoById(param.Id).Unwrap().(*users.UserModel)
	upl := userprofitlog.UserProfitLog{}
	upl.ParentId = param.ParentId
	upl.UserId = param.Id
	upl.UserName = param.UserName
	upl.OperationUserId = userId
	upl.OperationUserName = userName
	upl.OperateIP = ctx.ClientIP()
	upl.IsPlace = 1
	upl.Change = int8(userInfo.ProfitProportion)
	upl.ProfitProportion = int8(param.ProfitProportion)
	upl.Description = "修改商户用户"

	dingo.Task(logic.NewLogsLogic().InsertUserProfitLogLogic, func() {}, upl, param, userInfo) // 添加订单操作日志

	Response(ctx)("", CodeUpdateSuccess,
		dao.NewUserDao().UpdatePlaceUser(param).Unwrap())(OK)
}

func HandleGetWithdrawalSettingInfo(c *gin.Context) {
	isPlace, err := helper.GetIsPlaceFromCtx(c)
	if err != nil {
		Response(c)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}

	isAdmin, err := helper.GetIsAdminFromCtx(c)
	if err != nil {
		Response(c)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	isType := uint8(1)

	//运营商
	if isPlace == 0 && isAdmin == 2 {
		isType = 1
	}

	//代理商
	if isPlace == 0 && isAdmin != 2 {
		isType = 1
	}

	if isPlace == 1 {
		isType = 2
	}

	param := &request.AdminUserInsertReq{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	Response(c)("", CodeUpdateSuccess,
		dao.NewCashDao().GetWithdrawalSettingInfo(isType).Unwrap())(OK)
}

//查询所有用户
func HandleGetUser(c *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(c)
	if err != nil {
		Response(c)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}

	param := &struct {
		UserName string `json:"userName" form:"userName" `
	}{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	Response(c)("", CodeUpdateSuccess, dao.NewUserDao().GetAllUser(param.UserName, userId).Unwrap().([]*users.AgentInfo))(OK)
}

func HandleGetUserByPhone(ctx *gin.Context) {
	// 请求参数处理
	param := &struct {
		Phone  string `form:"phone"`
		UserId int    `form:"userId"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	// 分页信息
	Response(ctx)(
		"",
		CodeSuccess,
		dao.NewUserDao().CheckUserInfoByPhone(param.Phone, param.UserId).Unwrap(),
	)(OK)
}

// HandleGetRoleListNoPager 查询角色列表 - 无参数，无分页
func HandleGetRoleListNoPager(ctx *gin.Context) {
	param := &struct {
		IsAdmin uint8 `json:"isAdmin" form:"isAdmin"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param))

	if param.IsAdmin == 0 {
		param.IsAdmin, _ = helper.GetIsAdminFromCtx(ctx)
	}

	Response(ctx)("", CodeSuccess, dao.NewRoleDao().GetRoleListByIsAdmin(int(param.IsAdmin)).Unwrap())(OK)
	//Response(ctx)("", CodeSuccess, dao.NewRoleDao().GetRoleListNoPager().Unwrap())(OK)
}

func HandleGetRoleListH5NoPager(ctx *gin.Context) {
	param := &struct {
		IsAdmin int `json:"isAdmin" form:"isAdmin"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param))

	Response(ctx)("", CodeSuccess, dao.NewRoleDao().GetRoleListByIsAdmin(param.IsAdmin).Unwrap())(OK)
	//Response(ctx)("", CodeSuccess, dao.NewRoleDao().GetRoleListNoPager().Unwrap())(OK)
}

func GetPlaceUserListByName(ctx *gin.Context) {
	//param := &request.UserList{}
	//dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()
	//param.IsAdmin = 3
	//param.IsPlace = 1
	//param.PageSize = 0
	//param.PageNo = 0
	userId, err := helper.GetUserIdFromCtx(ctx)
	IsAdmin, _ := helper.GetIsAdminFromCtx(ctx)
	IsPlace, _ := helper.GetIsPlaceFromCtx(ctx)
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}

	// 请求参数处理
	param := &request.UserList{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()
	param.UserLoginIsAdmin = IsAdmin
	param.UserLoginIsPlace = IsPlace
	param.ParentId = userId // 当前登录用户ID
	//param.IsAdmin = helper.TypeNumIsAdminAgent // 代理商
	//param.IsPlace = 1
	if param.Name == "" {
		param.PageSize = 10
		param.PageNo = 1
	}

	Response(ctx)("", CodeSuccess,
		dao.NewUserDao().GetPlaceUserList(param).Unwrap(),
	)(OK)
}

// 获取分公司用户列表
func HandleGetBranchUserListNoPager(ctx *gin.Context) {
	// 请求参数处理
	param := &request.UserList{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()
	param.PageNo = 0
	param.PageSize = 0
	param.ParentId = 2
	param.IsAdmin = helper.TypeNumIsAdminBranch
	//param.IsPlace = 3

	Response(ctx)("", CodeSuccess,
		dao.NewUserDao().GetBranchUserList(param).Unwrap(),
	)(OK)
}

// 获取登录帐号对应的员工列表
func GetH5UserListMaintainer(ctx *gin.Context) {
	param := &struct {
		Id           int `form:"id"`
		IsAdmin      int `form:"isAdmin"`      // 登录的角色
		MaintainerId int `form:"maintainerId"` // 维护者ID
	}{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()
	userId, err := helper.GetUserIdFromCtx(ctx) // 从上下文中获取用户是否为管理员
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}

	isAdmin, err := helper.GetIsAdminFromCtx(ctx) // 从上下文中获取用户是否为管理员
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}

	var staffList []*users.UserModel
	if param.MaintainerId > 0 && isAdmin == 2 { // 运营商修改商户
		// 获取维护者信息
		userInfo := dao.NewUserDao().GetUserInfoById(param.MaintainerId).Unwrap().(*users.UserModel)
		staffList = dao.NewUserDao().GetMaintainerListByParentId(userInfo.ParentID).Unwrap().([]*users.UserModel)
	} else {
		if isAdmin == 2 || isAdmin > helper.TypeNumIsAdminStaff { // 运营商、代理商
			staffList = dao.NewUserDao().GetMaintainerListByParentId(userId).Unwrap().([]*users.UserModel)
		} else {
			staffList = dao.NewUserDao().GetMaintainerListById(userId).Unwrap().([]*users.UserModel)
		}
	}

	Response(ctx)("", CodeSuccess, staffList)(OK)
}

//获取省市县
func HandleGetRegions(ctx *gin.Context) {
	param := &struct {
		RegionsId int `form:"regionsId"`
		Level     int `form:"level"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	Response(ctx)("", CodeSuccess, dao.NewPlaceDao().GetRegionsByLevel(param.Level).Unwrap())(OK)
}

//获取省市县
func HandleGetRegionsByParent(ctx *gin.Context) {
	param := &struct {
		Parent int `form:"parent"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	Response(ctx)("", CodeSuccess, dao.NewPlaceDao().GetRegionsListByParent(param.Parent).Unwrap())(OK)
}

// 查询网点关联用户
func HandleGetAdminOrPlace(c *gin.Context) {
	param := &struct {
		UserName string `json:"userName" form:"userName" `
	}{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	userId, _ := helper.GetUserIdFromCtx(c)
	IsAdmin, _ := helper.GetIsAdminFromCtx(c)

	Response(c)("", CodeUpdateSuccess, dao.NewUserDao().
		GetAdminUserOrPlaceUser(param.UserName, userId, IsAdmin).Unwrap().([]*users.AgentInfo))(OK)
}

//代理商列表
func HandleGetAgentUserList(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	IsAdmin, _ := helper.GetIsAdminFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	// 请求参数处理
	param := &request.UserList{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	param.UserLoginIsAdmin = IsAdmin
	param.ParentId = userId // 当前登录用户ID
	param.IsAdmin = IsAdmin // 代理商
	param.IsPlace = 0

	//userId := 2
	//param.UserLoginIsAdmin = 2
	//param.ParentId = 2 // 当前登录用户ID
	//param.IsAdmin = 3  // 代理商
	//param.IsPlace = 0

	data := dao.NewUserDao().WebAppGetAgentUserList(param)
	lists := data.Unwrap().([]*users.UserInfoWithAgent)

	//getAgentChildMap := make(map[int]int)
	//getAgentChild := dao.NewUserDao().WebAppGetAgentChild(userId).Unwrap().([]*users.GetAgentChild)
	//
	//for _, v := range getAgentChild {
	//	getAgentChildMap[v.ParentId] = v.Id
	//}

	//查询下级的网点总数
	getPlaceChildMap := make(map[int]int)
	getPlaceChild := dao.NewUserDao().WebAppGetPlaceChild(userId, IsAdmin).Unwrap().([]users.GetPlaceChild)

	for _, v := range getPlaceChild {
		getPlaceChildMap[v.UserId] = v.Num
	}
	//查询当前登录的用户下级的

	for _, lst := range lists {
		userInfo := dao.NewUserDao().GetUserInfoById(lst.ParentId).Unwrap().(*users.UserModel)
		lst.ParentName = userInfo.UserName + "-" + userInfo.Name

		if v, ok := getPlaceChildMap[lst.ID]; ok {
			lst.PlaceChildNum = v
		} else {
			lst.PlaceChildNum = 0
		}

		logic.NewUserLogic().FindAgentChildrenList(lst.ID, lst, IsAdmin)
	}

	Response(ctx)("", CodeSuccess, ResponseList{
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  (data.Val().(int64) + int64(param.PageSize) - 1) / int64(param.PageSize),
		Data:       data.Unwrap(),
	})(OK)
}

// 新增代理商用户
func HandleInsertAgentUser(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx) // 获取当前登录用户ID
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}

	userName, err := helper.GetUserNameFromCtx(ctx) // 获取当前登录用户名
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	isAdmin, _ := helper.GetIsAdminFromCtx(ctx)

	param := &request.AdminUserInsertReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()

	if isAdmin != helper.TypeNumIsAdminOperator {
		param.IsAdmin = isAdmin
	}

	id := dao.NewUserDao().InsertAgentUser(param).Unwrap().(int)
	if id <= 0 {
		Response(ctx)("新增失败", CodeError, true)(OK)
		return
	}
	//添加修改用户分成日志
	upl := userprofitlog.UserProfitLog{}
	upl.ParentId = param.ParentId
	upl.UserName = param.UserName
	upl.OperationUserId = userId
	upl.OperationUserName = userName
	upl.OperateIP = ctx.ClientIP()
	upl.Change = 0
	upl.IsPlace = 0
	upl.ProfitProportion = int8(param.ProfitProportion)
	upl.Description = "新增代理商用户"
	upl.UserId = id
	u := &users.UserModel{}
	dingo.Task(logic.NewLogsLogic().InsertUserProfitLogLogic, func() {}, upl, param, u) // 添加订单操作日志
	Response(ctx)("新增成功", CodeSuccess, true)(OK)
}

// 修改代理商用户
func HandleUpdateAgentUser(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx) // 获取当前登录用户ID
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}

	userName, err := helper.GetUserNameFromCtx(ctx) // 获取当前登录用户名
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}

	param := &request.AdminUserInsertReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()

	//添加修改用户分成日志

	//查询该用户修改前的分成比例
	userInfo := dao.NewUserDao().GetUserInfoById(param.Id).Unwrap().(*users.UserModel)
	upl := userprofitlog.UserProfitLog{}
	upl.ParentId = param.ParentId
	upl.UserId = param.Id
	upl.UserName = param.UserName
	upl.OperationUserId = userId
	upl.OperationUserName = userName
	upl.OperateIP = ctx.ClientIP()
	upl.IsPlace = 0
	upl.Change = int8(userInfo.ProfitProportion)
	upl.ProfitProportion = int8(param.ProfitProportion)
	upl.Description = "新增代理商用户"

	dingo.Task(logic.NewLogsLogic().InsertUserProfitLogLogic, func() {}, upl, param, userInfo) // 添加订单操作日志
	Response(ctx)("", CodeUpdateSuccess,
		dao.NewUserDao().UpdateAgentUser(param).Unwrap())(OK)

}

func HandleGetAllAgentUserList(ctx *gin.Context) {
	// 请求参数处理
	param := &struct {
		UserName string `form:"userName"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	fmt.Println("HandleGetAllAgentUserList :", param.UserName)
	// 分页信息
	Response(ctx)(
		"",
		CodeSuccess,
		dao.NewUserDao().GetAllAgentUserNoLoginUserList(param.UserName, userId).Unwrap(),
	)(OK)
}
